package com.lxitedu.utils;

import java.util.ArrayList;
import java.util.List;

import com.lxitedu.chain.processor.ResponseHandlerThread;

public class ThreadPool {

  private int                         maxThreadNumber = 10;
  private List<ResponseHandlerThread> threadList      = new ArrayList<ResponseHandlerThread>();

  public ThreadPool(Context context) {
    Object number = context.getValueMap().get("maxThreadNumber");
    if (number != null) {
      this.maxThreadNumber = (Integer) number;
    }
    ResponseHandlerThread thread = null;
    for (int i = 0; i < maxThreadNumber; i++) {
      thread = new ResponseHandlerThread(context);
      threadList.add(thread);
      thread.start();
    }
  }

  public boolean hasThreadActive() {
    for (ResponseHandlerThread thread : threadList) {
      if (thread.isActive()) {
        return true;
      }
    }
    return false;
  }

  public ResponseHandlerThread getThread() {
    for (ResponseHandlerThread thread : threadList) {
      if (!thread.isActive()) {
        return thread;
      }
    }
    return null;
  }

  @SuppressWarnings("deprecation")
  public void destroy() {
    for (Thread thread : threadList) {
      thread.destroy();
    }
  }

  public void setMaxThreadNumber(int maxThreadNumber) {
    this.maxThreadNumber = maxThreadNumber;
  }

  public int getMaxThreadNumber() {
    return maxThreadNumber;
  }

}
